$(function() {
	
	$('#feeType').select2({placeholder: '类型'});
	
	loadPrincipalPayPlan();
});

function feeTypeOnchange(){
	if($('#feeType').val() == 'PZ99'){
		$('#feeName').val('');
		$('#feeName').attr("readonly",true);
	}else{
		$('#feeName').attr("readonly",false);
	}
	
	jQuery("#principalPayPlanList").clearGridData();
}

function submitAddForm() {
	if(!validateFeePlan()){
		return false;
	}
	
	setPayListToInput();
	
	SubmitAndPreventSecond("addForm",function(){
		//document.addForm.action = "prdFeeOrYieldAdd.do";
	});
}

//重算时验证费用
function validateFeePlan() {
	var feeType = $('#feeType').val();
	if (null == feeType || feeType == "") {
		ctools.alert("类型不能为空!","","error");
		return false;
	}
	
	if(feeType != 'PZ99'){
		var feeName = $('#feeName').val();
		if (null == feeName || feeName == "") {
			ctools.alert("名称不能为空!","","error");
			return false;
		}
	}
	
	var rowData = jQuery("#principalPayPlanList").jqGrid('getRowData');
	if (rowData.length < 1) {
		ctools.alert("支付计划列表数据不能为空!","","error");
		return false;
	}else{
		var ids = jQuery("#principalPayPlanList").jqGrid('getDataIDs');
		for (var i = 0; i < ids.length; i++) {
			 var id = ids[i];
			 
			 var cashFlowsDate = $.trim($("#" + id + "_cashFlowsDate").val());
			 var expectPayDate = $.trim($("#" + id + "_expectPayDate").val());
			 var expectPayAmount = $.trim($("#" + id + "_expectPayAmount").val());
			 var bnsDate = $.trim($("#" + id + "_bnsDate").val());
			 var bnsAmt = $.trim($("#" + id + "_bnsAmt").val());
			 
			 if (null == cashFlowsDate || cashFlowsDate == "") {
					ctools.alert("支付计划列表中核算日不能为空!","","error");
					$("#" + id + "_cashFlowsDate").focus();
					return false;
			 }
			 if (null == expectPayDate || expectPayDate == "") {
					ctools.alert("支付计划列表中预计支付日不能为空!","","error");
					$("#" + id + "_expectPayDate").focus();
					return false;
			 }
			 if (null == expectPayAmount || expectPayAmount == "") {
					ctools.alert("支付计划列表中预计支付金额不能为空!","","error");
					$("#" + id + "_expectPayAmount").focus();
					return false;
			 }
			 
			 if((bnsDate != "" && bnsAmt == "")
					|| (bnsDate == "" && bnsAmt != "")){
				    ctools.alert("支付计划列表中实际支付日和实际支付金额同时必填或同时为空!","","error");
					//$("#" + id + "_bnsDate").focus();
					return false;
			 }
		}
		
		//var cashFlowsDates ="";
		for (var i = 0; i < ids.length; i++) {
			 var id = ids[i];
			
			 var cashFlowsDate = $.trim($("#" + id + "_cashFlowsDate").val());
			 var expectPayDate = $.trim($("#" + id + "_expectPayDate").val());
			 var bnsDate = $.trim($("#" + id + "_bnsDate").val());
			 if(feeType != 'PZ99'){
				 if (cashFlowsDate > expectPayDate) {
					 toastr.error("当类型不为客户本金时，支付列表中的核算日不能大于预计支付日");
			         return false;
				 }
			 }else{
				 if (cashFlowsDate != expectPayDate) {
					 toastr.error("当类型为客户本金时，支付列表中的核算日必须等于预计支付日");
			         return false;
				 } 
			 }
			 if(bnsDate!=''){
				 if (expectPayDate > bnsDate) {
					 toastr.error("支付列表中的预计支付日不能大于实际支付日");
			         return false;
				 }
			 }

			 if(ids.length > 1 && i != ids.length-1 ){
				var afterCashFlowsDate = $.trim($("#" + (parseInt(id)+1) + "_cashFlowsDate").val());
				if(afterCashFlowsDate <= cashFlowsDate){
					toastr.error("支付列表中的核算日必须顺序递增");
					return false;
				}
			 }
			 
			//cashFlowsDates += cashFlowsDate +",";
		}
		
//		cashFlowsDates = cashFlowsDates.substring(0, cashFlowsDates.length - 1);//去掉最后一个逗号;
//		var date = cashFlowsDates.split(",");
//		date.sort();		//排序
//		if(date.length >1){
//			 for(var k = 0; k < date.length ; k++){
//				 if((k+1)<date.length){
//					if(date[k] == date[k+1]){
//						toastr.error("支付列表中的核算日不能相等");
//						return false;
//					}
//				} 
//			}
//		}
		
	}
		
	return true;	
}

//设置值
function setPayListToInput(){

	var payList = "";
	payList = "[";
	
	rowData = jQuery("#principalPayPlanList").jqGrid('getRowData');		
    if(rowData.length>0){
    	var ids = jQuery("#principalPayPlanList").jqGrid('getDataIDs');
		for (var i = 0; i < ids.length; i++) {
			 var id = ids[i]; 
			 
			 var cashFlowsDate = $.trim($("#" + id + "_cashFlowsDate").val());
			 var expectPayDate = $.trim($("#"+ id +"_expectPayDate").val());
			 var expectPayAmount = $.trim($("#" + id + "_expectPayAmount").val());
			 var bnsDate = $.trim($("#"+ id +"_bnsDate").val());
			 var bnsAmt = $.trim($("#" + id + "_bnsAmt").val());
			 
			 if (null == bnsDate || bnsDate == "") {
				 bnsDate = "";
			 }
			 if (null == bnsAmt || bnsAmt == "") {
				 bnsAmt = "";
			 }
			 
			 payList += "{";
			 payList += "'cashFlowsDate':'" + cashFlowsDate + "',";replaceSpecialStr();
			 payList += "'expectPayDate':'" + expectPayDate + "',";
			 payList += "'expectPayAmount':'" + replaceSpecialStr(expectPayAmount) + "',";
			 payList += "'bnsDate':'" + bnsDate + "',";
			 payList += "'bnsAmt':'" + replaceSpecialStr(bnsAmt) + "'";
			 payList +="},";
		}
	}
	
    payList += "]";
	$("#payList").val(payList);//将值以json形式保存到文本框
}

//去掉逗号
function replaceSpecialStr(str){
	if(str !="" && str!=null){
		str = str.replace(/,/g,'');
	}
	return str;
}

//委托财产提取 
function loadPrincipalPayPlan(){

	$("#principalPayPlanList").jqGrid({
		caption: '',
		url:   '',
		datatype: "json",
		colNames: ['ID','核算日','预计支付日','预计支付金额','实际支付日','实际支付金额','操作'],    
		colModel: [
		          {name:'payId', index:'payId', width:40, align:'left',key:true, hidden:true, editable: true,sortable:false},
		          {name:'cashFlowsDate', index:'cashFlowsDate', width:40, align:'left',editable: true, sortable:false,
		        	  edittype:"text",
						editoptions:{ 
						size: 10, 
						maxlengh: 10,  
						dataInit: function(element) {  
							WASP_WIDGET.triggerDateStyleWithYMD("#"+element.id);
						}
					 }  
				  },
				  {name:'expectPayDate', index:'expectPayDate', width:40, align:'left',editable: true, sortable:false,
		        	  edittype:"text",
						editoptions:{ 
						size: 10, 
						maxlengh: 10,  
						dataInit: function(element) {  
							WASP_WIDGET.triggerDateStyleWithYMD("#"+element.id);
						}
					 }  
				  },
				  {name:'expectPayAmount', index:'expectPayAmount', width:40, align:'left', editable: true,sortable:false,
					  editoptions : {
							dataEvents : [
											{
												type : 'blur',
												fn : function(e) {
													var ids = this.id
															.split("_");
													var rowid = ids[0];
													checkIsNoNegaNum_r(rowid
															+ '_expectPayAmount','请输入大于等于0的数字');
													fmtNumAll152(rowid
															+ '_expectPayAmount');
												}
											},
											{
												type : 'focus',
												fn : function(e) {
													var ids = this.id
															.split("_");
													var rowid = ids[0];
													fmtNumFocus(rowid
															+ '_expectPayAmount');
												}
											} ]
								} 
				  },
				  {name:'bnsDate', index:'bnsDate', width:40, align:'left',editable: true, sortable:false,
		        	  edittype:"text",
						editoptions:{ 
						size: 10, 
						maxlengh: 10,  
						dataInit: function(element) {  
							WASP_WIDGET.triggerDateStyleWithYMD("#"+element.id);
						}
					 }  
				  },
				  {name:'bnsAmt', index:'bnsAmt', width:40, align:'left', editable: true,sortable:false,
					  editoptions : {
							dataEvents : [
											{
												type : 'blur',
												fn : function(e) {
													var ids = this.id
															.split("_");
													var rowid = ids[0];
													checkIsNoNegaNum_r(rowid
															+ '_bnsAmt','请输入大于等于0的数字');
													fmtNumAll152(rowid
															+ '_bnsAmt');
												}
											},
											{
												type : 'focus',
												fn : function(e) {
													var ids = this.id
															.split("_");
													var rowid = ids[0];
													fmtNumFocus(rowid
															+ '_bnsAmt');
												}
											} ]
								} 
				  },
			      {name:'option', index:'option', width:40, align:'left', sortable:false},
				  ],
	    rowNum:9999,        
		rowList:[100],
		prmNames: {
	        search: "search", 
	        page: "pageNo",
	        rows: "limit" 
	    },
	    postData:{
			//'sp[prjCode]': $("#prjCode").val(),
			//'sp[payType]': 'SY18'
		},
		autowidth: true,       
		height: 200,
		jsonReader: {  
			root: "items",       //结果集
			records: "total", //总记录数 
			total: "pageCount",	  //总页数
			page: "pageNo",	  //当前页 
			repeatitems : false       // (4)  
		},
		pager:"#principalPayPlanPage", 
		hidegrid: false,
		viewrecords: true, 
		rownumbers:true,
		rownumWidth: 50,
		editurl: 'clinetArray',
		loadui: 'disable',
		gridComplete: function() {
				var ids = jQuery("#principalPayPlanList").jqGrid('getDataIDs');
				for (var i = 0; i < ids.length; i++) {
					
					var deleteBtn = '<a href="javascript:void(0);" class="btn btn-link btn-jqgrid" title="删除" onclick="deleteRow(\'principalPayPlanList'
						+ '\',\''
						+ ids[i]
						+ '\');">删除</a>';
		            
					jQuery("#principalPayPlanList").jqGrid('setRowData', ids[i], {option: deleteBtn});
					jQuery('#principalPayPlanList').editRow(ids[i]);
				}

			}
		});
		jQuery("#principalPayPlanList").navGrid(
				'#principalPayPlanPage', {
					edit : false,
					add : false,
					del : false,
					search : false,
					refresh : false
				}).navButtonAdd('#principalPayPlanPage',
				{
					id : "principalPayPlanList_btnAdd",
					caption : "新增",
					buttonicon : "ui-icon-plus",
					position : "last",
					onClickButton : function() {
						var payNewRowId = selectMaxId("principalPayPlanList");
						var entrustedPropertyDataRow = {
								payId : payNewRowId,
								cashFlowsDate : "",
								expectPayDate : "",
								expectPayAmount : "",
								bnsDate : "",
								bnsAmt : "",
								option : ""
						};
						addRow("principalPayPlanList",entrustedPropertyDataRow,payNewRowId);
					}
				});

		jQuery("#principalPayPlanList").jqGrid('setFrozenColumns');
		jqGridResize($("#principalPayPlanList"));
		//doResize("principalPayPlanList");
		jQuery("#principalPayPlanList").clearGridData();
	}

//新增行
var addRow = function(table,dataRow,payNewRowId) {
	var selectedId = $("#"+table).jqGrid("getGridParam","selrow");
	if (selectedId) {
	$("#"+table).jqGrid("addRowData", payNewRowId,
			dataRow, "after", selectedId);
	} else {
	$("#"+table).jqGrid("addRowData", payNewRowId,
			dataRow, "last");
	}
}

//删除行
var deleteRow = function(table,selectedId) {
	if (!selectedId) {
		selectedId = $("#"+table).jqGrid("getGridParam","selrow");
	}
	$("#"+table).jqGrid('delRowData', selectedId);
}


//获取对应表格行最大值
function selectMaxId(table){
	var maxId = 0;
	var ids = $("#"+table).jqGrid('getDataIDs');
	if(ids.length > 0){
	 	maxId = Math.max.apply(null,ids);
	} 
	maxId = parseInt(maxId) + 1;
	return maxId;
}